package cn.zhz.cloud.gateway.filter;

import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.zhz.cloud.gateway.config.AuthRule;
import cn.zhz.cloud.gateway.util.AuthVerify;
import cn.zhz.cloud.token.dto.CurrentUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.List;

import static cn.zhz.cloud.token.constant.TokenConstant.SA_MODEL_KEY_USER;

/**
 * 自定义局部过滤器
 */
@Component
@Slf4j
public class OrderServerGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthRule> {

    /**
     * 定义构造器(必须)
     */
    public OrderServerGatewayFilterFactory() {
        super(AuthRule.class);
    }

    /**
     * 重写拦截方法(必须)
     */
    @Override
    public GatewayFilter apply(AuthRule authRule) {

        return (exchange, chain) -> AuthVerify.verify(exchange, chain, (ex) -> {
            // 获取请求对象
            ServerHttpRequest request = ex.getRequest();

            // 全部都需要验证登录
            SaRouter.match("/**").notMatch(authRule.getIgnoreUrls()).check(StpUtil::checkLogin);
            // 放开请求
            SaRouter.match(authRule.getIgnoreUrls()).check(() -> log.debug("{}请求被放开", request.getPath())).stop();
            // 动态权限
            List<AuthRule.Rule> rules = authRule.getRules();
            if (CollUtil.isNotEmpty(rules)) {
                rules.forEach(rule -> SaRouter.match(rule.getPatterns()).check(() -> StpUtil.checkPermission(rule.getPermissionCode())));
            }

        });
    }

}
